﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using System.Collections.Generic;
using System.IO;

namespace WaferImage
{
    public partial class frmMain : Form
    {
        #region CLASSDATA
        private bool _isMouseDown = false;
        private Point _mousePosA = new Point(0, 0);
        private string ImageResults = null;   //保存用来在textbox中显示的结果
        private double[] evalute_value = new double[10]; //保存隐裂脏污表崩的结果
        private double UDCrack_value1 = -999;   //保存侧崩图像的结果
        private double UDCrack_value2 = -999;//保存侧崩图像的结果

        private int saw_value1 = -999;//保存线痕图像的结果,整副图像的Otsu分割阈值
        private double saw_value2 = -999;//保存线痕图像的结果,宽度均匀性的比例值

        private Graphics ga;    //用来在图片上划线时使用 
        private Bitmap _bitmap; //存放加载的图片
        private PointF location;    //用来保存picturebox控件的位置        
        private bool hasImage = false;    //picturebox是否加载图像,首次运行有效
        private bool draw = false;
        //private bool imageQuality = false;  //图像质量是否合格
        private string[] imgPath;   //选取多个文件时,保存路径
        private int numPic = 0; //选取的图片个数
        private int currentPic = 0; //  当前浏览的第几个图片
        private Config config;


        #endregion CLASSDATA

        #region   画ROI
        bool isDrag = false;
        Rectangle theRectangle = new Rectangle(new Point(0, 0), new Size(0, 0));
        Point startPoint;
        private Graphics ig;
        bool IsDrawretangle = false;
        bool IsSaveimage = false;
        bool IsDisplayGray = false;


        #endregion

        #region   单项检测结果
        /// <summary>
        /// 线痕
        /// </summary>
        List<string> SawMarkResult = new List<string>();

        /// <summary>
        /// 上下左右侧崩
        /// </summary>
        List<string> LrFbChipsResult = new List<string>();

        /// <summary>
        /// 表崩
        /// </summary>
        List<string> ChipResult = new List<string>();
        /// <summary>
        /// 脏污
        /// </summary>
        List<string> StainsResult = new List<string>();

        /// <summary>
        /// 隐裂
        /// </summary>
        List<string> CracksResult = new List<string>();
        #endregion
        public frmMain()
        {
            InitializeComponent();
            imgPictureBox.MouseWheel += imgPanel_MouseWheel;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            config = new Config();
            config.Load(ref config);
            try
            {
                propertyGrid1.SelectedObject = config;
            }
            catch
            {

            }
          //  propertyGrid1.SelectedObject = config;
            pgConfig.SelectedObject = config;
            imgPictureBox.MouseWheel += imgPanel_MouseWheel;

        }

        private void imgPanel_MouseWheel(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Delta > 0)
                {
                    this._zoom *= 1.1;
                    this.ZoomWork(1.1, e);
                }
                else
                {
                    this._zoom *= 0.9;
                    this.ZoomWork(0.9, e);
                }
            }
            catch (Exception ex)
            {

            }
        }
        /// <summary> 选择要检测的图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelectImage_Click(object sender, EventArgs e)
        {
            var sfDialog = new OpenFileDialog();
            sfDialog.Multiselect = true;
           // sfDialog.Filter = "Bmp文件|*.bmp";
            sfDialog.Filter = "(*.jpg,*.png,*.jpeg,*.bmp,*.gif)|*.jgp;*.png;*.jpeg;*.bmp;*.gif|All files(*.*)|*.*";
            if (DialogResult.OK == sfDialog.ShowDialog())
            {
                imgPath = sfDialog.FileNames;

                LoadPicture(sfDialog.FileName);
                numPic = imgPath.GetLength(0);
                currentPic = 1;
                lblPicNum.Text = "1/" + numPic.ToString();
            }
        }

        public void LoadPicture(string path)
        {
            lbFilePath.Text = path;
            _bitmap = new Bitmap(path);

            imgPictureBox.Width = _bitmap.Width/16;
            imgPictureBox.Height = _bitmap.Height/16;
            imgPictureBox.Image = _bitmap;
            imgPictureBox.Location = new Point(0, 0);
            using (Image img = Image.FromFile(path))
            {
               if (IsIndexedPixelFormat(img.PixelFormat))
                {
                    Bitmap bmp = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb);
                    ga = Graphics.FromImage(bmp);
                }
                else
                {
                    ga = Graphics.FromImage(imgPictureBox.Image);
                }         
            }

            location = imgPictureBox.Location;
            hasImage = true;
        }

        /// <summary> 判断图片是否索引像素格式,是否是引发异常的像素格式
        /// </summary>
        /// <param name="imagePixelFormat">图片的像素格式</param>
        /// <returns></returns>
        private bool IsIndexedPixelFormat(System.Drawing.Imaging.PixelFormat imagePixelFormat)
        {
            PixelFormat[] pixelFormatArray = {
                                            PixelFormat.Format1bppIndexed
                                            ,PixelFormat.Format4bppIndexed
                                            ,PixelFormat.Format8bppIndexed
                                            ,PixelFormat.Undefined
                                            ,PixelFormat.DontCare
                                            ,PixelFormat.Format16bppArgb1555
                                            ,PixelFormat.Format16bppGrayScale
                                        };
            foreach (PixelFormat pf in pixelFormatArray)
            {
                if (imagePixelFormat == pf)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>检测图像质量
        /// </summary>
        private void CheckPic()
        {


            if (_bitmap != null)
            {
                if (rbSaw.Checked)  //线痕
                {
                    SawCheck(_bitmap.Clone() as Bitmap);    //_bitmap will be changed after cal                     
                    UpdateImageResults();
                    draw = true;
                    imgPictureBox.Invalidate();

                }
                else if (rbLrFbChips.Checked)   //侧崩
                {
                    LrFbChipsCheck(_bitmap.Clone() as Bitmap);
                    UpdateImageResults();
                    draw = true;

                    imgPictureBox.Invalidate();
                }

                else if (rbCracks.Checked)   //隐裂
                {
                    CracksCheck(_bitmap.Clone() as Bitmap);
                    UpdateImageResults();
                    draw = true;

                    imgPictureBox.Invalidate();
                }
                else if (rbStains.Checked)   //脏污
                {
                    StainsCheck(_bitmap.Clone() as Bitmap);
                    UpdateImageResults();
                    draw = true;

                    imgPictureBox.Invalidate();
                }
                else if (rbChips.Checked)   //表崩
                {
                    ChipsCheck(_bitmap.Clone() as Bitmap);
                    UpdateImageResults();
                    draw = true;

                    imgPictureBox.Invalidate();
                }
            }
        }

        #region 灰度值算法

        float grayStdLow = 100;   //灰度值标准 ,没有意义    
        float grayStdUp = 100;  //灰度值标准,没有意义   
        float factorStdLow = 0.5F;  //清晰度或长宽比标准,没有意义   
        float factorStdUp = 0.5F;   //清晰度或长宽比标准,没有意义   

        /// <summary> 线痕图片的灰度值检测
        /// </summary>
        /// <param name="bmp"></param>
        private void SawCheck(Bitmap bmp)
        {
            unsafe
            {
                var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
                BitmapData bmpdata = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
                IntPtr ptr1 = bmpdata.Scan0;
                int value1 = -999;
                double value2 = -999;

                IntPtr pt11 = Marshal.AllocHGlobal(10);
                //调算法dll来计算各区域灰度值 
                EvaluteImageCore.SawCheck(ptr1, bmp.Width, bmp.Height, grayStdLow, factorStdUp, ref value1, ref value2);
                saw_value1 = value1;
                saw_value2 = value2;
                //saw_value3 = value3;
                bmp.UnlockBits(bmpdata);
            }

            SawMarkResult = new List<string>();
            if (saw_value1 > config.SawCheckGrayLow && saw_value1 < config.SawCheckGrayUp)
            {
                SawMarkResult.Add("OK");
            }
            else
            {
                SawMarkResult.Add("NG");
            }
            if (saw_value2 < config.SawCheckWidthUp && saw_value2 > config.SawCheckWidthLow)
            {
                SawMarkResult.Add("OK");
            }
            else
            {
                SawMarkResult.Add("NG");
            }



            if (!((saw_value1 > config.SawCheckGrayLow && saw_value1 < config.SawCheckGrayUp) && (saw_value2 < config.SawCheckWidthUp && saw_value2 > config.SawCheckWidthLow)))
            {
                lblQuality.Text = "图像不合格";
                lblQuality.ForeColor = Color.Crimson;
            }
            else
            {
                lblQuality.Text = "图像合格";
                lblQuality.ForeColor = Color.RoyalBlue;
            }
        }

        /// <summary> 侧崩图像的灰度值检测
        /// </summary>
        /// <param name="bmp"></param>
        private void LrFbChipsCheck(Bitmap bmp)
        {
            unsafe
            {
                var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
                BitmapData bmpdata = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
                IntPtr ptr1 = bmpdata.Scan0;
                double[] value = new double[2];
                double value1 = -999;
                double value2 = -999;
                IntPtr pt11 = Marshal.AllocHGlobal(10);
                //调算法dll来计算各区域灰度值 
                EvaluteImageCore.UDCrackCheck(ptr1, bmp.Width, bmp.Height, grayStdUp, factorStdLow, ref value1, ref value2);
                UDCrack_value1 = value1;
                UDCrack_value2 = value2;
                bmp.UnlockBits(bmpdata);
            }

            LrFbChipsResult = new List<string>();

            if (UDCrack_value1 > config.LrFbChipsCheckGrayLow && UDCrack_value1 < config.LrFbChipsCheckGrayUp)
            {
                LrFbChipsResult.Add("OK");
            }
            else
            {
                LrFbChipsResult.Add(" NG");
            }

            if (UDCrack_value2 < config.LrFbChipsCheckFactorUp && UDCrack_value2 > config.LrFbChipsCheckFactorLow)
            {
                LrFbChipsResult.Add("OK");
            }
            else
            {
                LrFbChipsResult.Add("NG");
            }



            if (!((UDCrack_value1 > config.LrFbChipsCheckGrayLow && UDCrack_value1 < config.LrFbChipsCheckGrayUp) && (UDCrack_value2 < config.LrFbChipsCheckFactorUp && UDCrack_value2 > config.LrFbChipsCheckFactorLow)))
            {
                lblQuality.Text = "图像不合格";
                lblQuality.ForeColor = Color.Crimson;
            }
            else
            {
                lblQuality.Text = "图像合格";
                lblQuality.ForeColor = Color.Green;

            }
        }


        /// <summary> 表崩图片的灰度值检测
        /// </summary>
        /// <param name="bmp"></param>
        private void ChipsCheck(Bitmap bmp)
        {
            unsafe
            {
                var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
                BitmapData bmpdata = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
                
                //byte* pSrc = (byte*)bmpdata.Scan0;
                IntPtr bmpPtr = bmpdata.Scan0;
                double[] value = new double[20];
                //调算法dll来计算各区域灰度值 
                //EvaluteImageCore.evalute_image(((UInt64)pSrc).ToString(), bmp.Width, bmp.Height, value);
                EvaluteImageCore.evalute_image(bmpPtr, bmp.Width, bmp.Height, value);
                evalute_value = value;
                bmp.UnlockBits(bmpdata);
            }


            bool good = true;
            for (int i = 0; i < 10; i++)
            {
                if (evalute_value[i] > config.ChipsGrayLow.Temp[i] && evalute_value[i] < config.ChipsGrayUp.Temp[i])
                {
                    continue;
                }
                else
                {
                    good = false;
                    break;
                }
            }
            if (!(evalute_value[10] > config.ChipsDistortion && evalute_value[11] > config.ChipsLaplacian &&
                  evalute_value[12] > config.ChipsSobel && evalute_value[13] > config.ChipsSdev))
            {
                good = false;
            }


            ChipResult = new List<string>();

            for (int i = 0; i < 10; i++)
            {
                if (evalute_value[i] > config.ChipsGrayLow.Temp[i] && evalute_value[i] < config.ChipsGrayUp.Temp[i])
                {
                    ChipResult.Add("OK");
                }
                else
                {
                    ChipResult.Add("NG");
                }
            }
            if (evalute_value[11] > config.ChipsDistortion)
            {
                ChipResult.Add("OK");
            }

            else
            {
                ChipResult.Add("NG");
            }


            if (evalute_value[12] > config.ChipsLaplacian)
            {
                ChipResult.Add("OK");
            }
            else
            {
                ChipResult.Add("NG");
            }


            if (evalute_value[13] > config.ChipsSobel)
            {
                ChipResult.Add("OK");
            }
            else
            {
                ChipResult.Add("NG");
            }

            if (evalute_value[14] > config.ChipsSdev)
            {
                ChipResult.Add("OK");
            }
            else
            {
                ChipResult.Add("NG");
            }


            if (!(good))
            {
                lblQuality.Text = "图像不合格";
                lblQuality.ForeColor = Color.Crimson;
            }
            else
            {
                lblQuality.Text = "图像合格";
                lblQuality.ForeColor = Color.Green;

            }
        }




        /// <summary> 脏污图片的灰度值检测
        /// </summary>
        /// <param name="bmp"></param>
        private void StainsCheck(Bitmap bmp)
        {
            unsafe
            {
                var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
                BitmapData bmpdata = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
                //byte* pSrc = (byte*)bmpdata.Scan0;
                IntPtr bmpPtr = bmpdata.Scan0;
                double[] value = new double[20];
                //调算法dll来计算各区域灰度值 
                //EvaluteImageCore.evalute_image(((UInt64)pSrc).ToString(), bmp.Width, bmp.Height, value);
                EvaluteImageCore.evalute_image(bmpPtr, bmp.Width, bmp.Height, value);
                evalute_value = value;
                bmp.UnlockBits(bmpdata);
            }
            bool good = true;
            for (int i = 0; i < 10; i++)
            {
                if (evalute_value[i] > config.StainsGrayLow.Temp[i] && evalute_value[i] < config.StainsGrayUp.Temp[i])
                {
                    continue;
                }
                else
                {
                    good = false;
                    break;
                }
            }
            if (!(evalute_value[10] > config.StainsDistortion && evalute_value[11] > config.StainsLaplacian &&
                  evalute_value[12] > config.StainsSobel && evalute_value[13] > config.StainsSdev))
            {
                good = false;
            }



            StainsResult = new List<string>();

            for (int i = 0; i < 10; i++)
            {
                if (evalute_value[i] > config.StainsGrayLow.Temp[i] && evalute_value[i] < config.StainsGrayUp.Temp[i])
                {
                    StainsResult.Add("OK");
                }
                else
                {
                    StainsResult.Add("NG");
                }
            }
            if (evalute_value[11] > config.StainsDistortion)
            {
                StainsResult.Add("OK");
            }
            else
            {
                StainsResult.Add("NG");
            }

            if (evalute_value[12] > config.StainsLaplacian)
            {
                StainsResult.Add("OK");
            }
            else
            {
                StainsResult.Add("NG");
            }

            if (evalute_value[13] > config.StainsSobel)
            {
                StainsResult.Add("OK");
            }
            else
            {
                StainsResult.Add("NG");
            }

            if (evalute_value[14] > config.StainsSdev)
            {
                StainsResult.Add("OK");
            }
            else
            {
                StainsResult.Add("NG");
            }



            if (!(good))
            {
                lblQuality.Text = "图像不合格";
                lblQuality.ForeColor = Color.Crimson;
            }
            else
            {
                lblQuality.Text = "图像合格";
                lblQuality.ForeColor = Color.Green;

            }












        }

        /// <summary> 隐裂图片的灰度值检测
        /// </summary>
        /// <param name="bmp"></param>
        private void CracksCheck(Bitmap bmp)
        {
            unsafe
            {
                var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
                BitmapData bmpdata = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.DontCare);
                //byte* pSrc = (byte*)bmpdata.Scan0;
                IntPtr bmpPtr = bmpdata.Scan0;
                double[] value = new double[20];
                //调算法dll来计算各区域灰度值 
                //EvaluteImageCore.evalute_image(((UInt64)pSrc).ToString(), bmp.Width, bmp.Height, value);
                EvaluteImageCore.evalute_image(bmpPtr, bmp.Width, bmp.Height, value);
                evalute_value = value;
                bmp.UnlockBits(bmpdata);
            }
            bool good = true;
            for (int i = 0; i < 10; i++)
            {
                if (evalute_value[i] > config.CracksGrayLow.Temp[i] && evalute_value[i] < config.CracksGrayUp.Temp[i])
                {
                    continue;
                }
                else
                {
                    good = false;
                    break;
                }
            }
            if (!(evalute_value[10] > config.CracksDistortion && evalute_value[11] > config.CracksLaplacian &&
                evalute_value[12] > config.CracksSobel && evalute_value[13] > config.CracksSdev))
            {
                good = false;
            }


            CracksResult = new List<string>();
            for (int i = 0; i < 10; i++)
            {
                if (evalute_value[i] > config.CracksGrayLow.Temp[i] && evalute_value[i] < config.CracksGrayUp.Temp[i])
                {
                    CracksResult.Add("OK");
                }
                else
                {
                    CracksResult.Add("NG");
                }
            }
            if (evalute_value[11] > config.CracksDistortion)
            {
                CracksResult.Add("OK");
            }
            else
            {
                CracksResult.Add("NG");
            }

            if (evalute_value[12] > config.CracksLaplacian)
            {
                CracksResult.Add("OK");
            }
            else
            {
                CracksResult.Add("NG");
            }

            if (evalute_value[13] > config.CracksSobel)
            {
                CracksResult.Add("OK");
            }
            else
            {
                CracksResult.Add("NG");
            }

            if (evalute_value[14] > config.CracksSdev)
            {
                CracksResult.Add("OK");
            }
            else
            {
                CracksResult.Add("NG");
            }





            if (!(good))
            {
                lblQuality.Text = "图像不合格";
                lblQuality.ForeColor = Color.Crimson;
            }
            else
            {
                lblQuality.Text = "图像合格";
                lblQuality.ForeColor = Color.Green;

            }
        }
        #endregion 灰度值算法

        #region DrawOnPic

        /// <summary> 在加载的图像上绘制分割线
        /// </summary>
        /// <param name="g"></param>
        private void DrawLine(Graphics g)
        {
            if (rbCracks.Checked || rbStains.Checked || rbChips.Checked)    //隐裂,脏污,表崩
            {
                Brush brushLine = new SolidBrush(Color.FromArgb(0, 255, 255));
                Pen pen = new Pen(brushLine, 3);

                int spaceX = imgPictureBox.Width / 3;   //分割线X方向上的间距
                int spaceY = imgPictureBox.Height / 3;  //分割线Y方向上的间距

                PointF pointUp1 = new PointF(location.X + spaceX, location.Y);
                PointF pointUp2 = new PointF(location.X + 2 * spaceX, location.Y);
                PointF pointDown1 = new PointF(location.X + spaceX, location.Y + imgPictureBox.Height);
                PointF pointDown2 = new PointF(location.X + 2 * spaceX, location.Y + imgPictureBox.Height);
                PointF pointLeft1 = new PointF(location.X, location.Y + spaceY);
                PointF pointLeft2 = new PointF(location.X, location.Y + 2 * spaceY);
                PointF pointRight1 = new PointF(location.X + imgPictureBox.Width, location.Y + spaceY);
                PointF pointRight2 = new PointF(location.X + imgPictureBox.Width, location.Y + 2 * spaceY);

                g.DrawLine(pen, pointUp1, pointDown1);
                g.DrawLine(pen, pointUp2, pointDown2);
                g.DrawLine(pen, pointLeft1, pointRight1);
                g.DrawLine(pen, pointLeft2, pointRight2);

                imgPictureBox.Invalidate();
            }
          
        }


        /// <summary> 在图片上显示各区域的灰度值
        /// </summary>
        /// <param name="g"></param>
        private void DrawText(Graphics g)
        {

            if (rbCracks.Checked || rbStains.Checked || rbChips.Checked)    //隐裂,脏污,表崩
            {              
                Font f = new System.Drawing.Font("宋体", imgPictureBox.Width / 45, FontStyle.Bold);             
                int spaceX = imgPictureBox.Width / 6;   //X方向上的间距
                int spaceY = imgPictureBox.Height / 6;  //Y方向上的间距
                PointF[] pointText = new PointF[9];
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        pointText[3 * i + j] = new PointF(location.X + 2 * j * spaceX + spaceX / 3, location.Y + 2 * i * spaceY + spaceY / 2);
                    }
                }

                for (int i = 1; i < 10; i++)
                {
                    List<string> _result = new List<string>();
                    Brush brushText;

                    try
                    {

                        if (rbStains.Checked)
                        {
                            _result = StainsResult;
                        }
                        if (rbCracks.Checked)
                        {
                            _result = CracksResult;
                        }
                        if (rbChips.Checked)
                        {
                            _result = ChipResult;
                        }
                        if (_result.Count == 0)
                        {

                           // MessageBox.Show("请检测图片！");
                        }
                        else
                        {
                            if (_result[i] == "OK")
                            {
                                brushText = new SolidBrush(Color.FromArgb(0, 255, 0));
                            }
                            else
                            {
                                brushText = new SolidBrush(Color.FromArgb(255, 0, 0));
                            }
                            g.DrawString("区域" + i.ToString() + "灰度：" + ((int)evalute_value[i]).ToString(), f, brushText, pointText[i - 1]);
                        }
                    
                    }
                    catch
                    { }



                   
                }
                imgPictureBox.Invalidate();
            }
            else if (rbLrFbChips.Checked)   //侧崩
            {
                Font f = new System.Drawing.Font("宋体", imgPictureBox.Width / 45, FontStyle.Bold);
                Brush brushText = new SolidBrush(Color.FromArgb(255, 0, 0));
                PointF pointChips = new PointF(location.X + 5, location.Y + 5);
                g.DrawString("平均灰度值：" + string.Format("{0:F}", UDCrack_value1) + "    清晰度：" + string.Format("{0:F}", UDCrack_value2), f, brushText, pointChips);
                imgPictureBox.Invalidate();
            }
            else if (rbSaw.Checked)   //线痕
            {
                Font f = new System.Drawing.Font("宋体", imgPictureBox.Width / 55, FontStyle.Bold);
                Brush brushText = new SolidBrush(Color.FromArgb(255, 0, 0));
                PointF pointSaw = new PointF(location.X + 5, location.Y + 5);
                g.DrawString("分割阈值：" + string.Format("{0:F}", saw_value1) + "  宽度均匀性：" + string.Format("{0:F}", saw_value2), f, brushText, pointSaw);
                imgPictureBox.Invalidate();
            }

        }

        private void imgPictureBox_Paint(object sender, PaintEventArgs e)
        {
          if(chbDisplaynineGray.Checked==true)
          {
              if (draw)
              {
                  DrawLine(e.Graphics);
                  DrawText(e.Graphics);
                  draw = false;
                  imgPictureBox.Refresh(); 
              }

          }
            
            
         
        }

        #endregion DrawOnPic

        /// <summary> 更新textbox内的结果显示
        /// </summary>
        /// <param name="_results"></param>
        public void UpdateImageResults()
        {
            txtImageResults.Clear();
            if (rbSaw.Checked)
            {
                txtImageResults.Clear();
                ImageResults = "线痕图像" + "\r\n" + "\r\n";
                ImageResults += "图像质量" + "\r\n";
                ImageResults += "分割阈值:     " + saw_value1.ToString() + "  " + SawMarkResult[0] + "\r\n";

                ImageResults += "宽度均匀性:   " + string.Format("{0:F}", saw_value2) + "  " + SawMarkResult[1] + "\r\n";
                //ImageResults += "有效区域长度: " + saw_value3.ToString() + "\r\n";
                txtImageResults.Text = ImageResults + "\r\n";
                ImageResults = "";
            }
            if (rbLrFbChips.Checked)
            {
                txtImageResults.Clear();
                ImageResults = "侧崩图像" + "\r\n" + "\r\n";
                ImageResults += "图像质量" + "\r\n";
                ImageResults += "平均灰度值:     " + string.Format("{0:F}", UDCrack_value1) + "  " + LrFbChipsResult[0] + "\r\n";
                ImageResults += "清晰度:         " + string.Format("{0:F}", UDCrack_value2) + "  " + LrFbChipsResult[0] + "\r\n";
                txtImageResults.Text = ImageResults + "\r\n";
                ImageResults = "";

            }
            if (rbCracks.Checked)
            {
                ImageResults = "隐裂图像" + "\r\n" + "\r\n";
                ImageResults += "图像质量" + "\r\n";
                ImageResults += "平均灰度值:     " + ((int)evalute_value[0]).ToString() + "  " + CracksResult[0] + "\r\n";
                ImageResults += "灰度最大值:    " + ((int)evalute_value[14]).ToString() + "\r\n";
                ImageResults += "灰度最小值:    " + ((int)evalute_value[15]).ToString() + "\r\n";
                for (int i = 1; i < 10; i++)
                {
                    ImageResults += "区域" + i.ToString() + "灰度值:    " + ((int)evalute_value[i]).ToString() + "  " + CracksResult[i] + "\r\n";
                }
                ImageResults += "\r\n" + "图像畸变:    " + Math.Round(evalute_value[10], 2).ToString() + "  " + CracksResult[10] + "\r\n";
                ImageResults += "拉普拉斯值:    " + Math.Round(evalute_value[11], 2) + "  " + CracksResult[11] + "\r\n";
                ImageResults += "sobel值:    " + Math.Round(evalute_value[12], 2).ToString() + "  " + CracksResult[12] + "\r\n";
                ImageResults += "标准差:    " + Math.Round(evalute_value[13], 2).ToString() + "  " + CracksResult[13] + "\r\n";

                txtImageResults.Text = ImageResults + "\r\n";
                ImageResults = "";
            }
            if (rbStains.Checked)
            {
                ImageResults = "脏污图像" + "\r\n" + "\r\n";
                ImageResults += "图像质量" + "\r\n";
                ImageResults += "平均灰度值:     " + ((int)evalute_value[0]).ToString() + "  " + StainsResult[0] + "\r\n";
                ImageResults += "灰度最大值:    " + ((int)evalute_value[14]).ToString() + "\r\n";
                ImageResults += "灰度最小值:    " + ((int)evalute_value[15]).ToString() + "\r\n";
                for (int i = 1; i < 10; i++)
                {
                    ImageResults += "区域" + i.ToString() + "灰度值:    " + ((int)evalute_value[i]).ToString() + "  " + StainsResult[i] + "\r\n";
                }
                ImageResults += "\r\n" + "图像畸变:    " + Math.Round(evalute_value[10], 2).ToString() + "  " + StainsResult[10] + "\r\n";
                ImageResults += "拉普拉斯值:    " + Math.Round(evalute_value[11], 2) + "  " + StainsResult[11] + "\r\n";
                ImageResults += "sobel值:    " + Math.Round(evalute_value[12], 2).ToString() + "  " + StainsResult[12] + "\r\n";
                ImageResults += "标准差:    " + Math.Round(evalute_value[13], 2).ToString() + "  " + StainsResult[13] + "\r\n";

                txtImageResults.Text = ImageResults + "\r\n";
                ImageResults = "";
            }
            if (rbChips.Checked)
            {
                ImageResults = "表崩图像" + "\r\n" + "\r\n";
                ImageResults += "图像质量" + "\r\n";
                ImageResults += "平均灰度值:     " + ((int)evalute_value[0]).ToString() + "  " + ChipResult[0] + "\r\n";
                ImageResults += "灰度最大值:    " + ((int)evalute_value[14]).ToString() + "\r\n";
                ImageResults += "灰度最小值:    " + ((int)evalute_value[15]).ToString() + "\r\n";
                for (int i = 1; i < 10; i++)
                {
                    ImageResults += "区域" + i.ToString() + "灰度值:    " + ((int)evalute_value[i]).ToString() + "  " + ChipResult[i] + "\r\n";
                }
                ImageResults += "\r\n" + "图像畸变:    " + Math.Round(evalute_value[10], 2).ToString() + "  " + ChipResult[10] + "\r\n";
                ImageResults += "拉普拉斯值:    " + Math.Round(evalute_value[11], 2) + "  " + ChipResult[11] + "\r\n";
                ImageResults += "sobel值:    " + Math.Round(evalute_value[12], 2).ToString() + "  " + ChipResult[12] + "\r\n";
                ImageResults += "标准差:    " + Math.Round(evalute_value[13], 2).ToString() + "  " + ChipResult[13] + "\r\n";
                txtImageResults.Text = ImageResults + "\r\n";
                ImageResults = "";
            }
        }

        private void btnLeft_Click(object sender, EventArgs e)
        {
            if (hasImage)
            {
                if (currentPic == 1)
                {
                    LoadPicture(imgPath[numPic - 1]);
                    currentPic = numPic;
                }
                else
                {
                    LoadPicture(imgPath[currentPic - 2]);
                    currentPic--;
                }
                lblPicNum.Text = currentPic.ToString() + "/" + numPic.ToString();
                CheckPic();
            }

        }

        private void btnRight_Click(object sender, EventArgs e)
        {
            if (hasImage)
            {
                if (currentPic == numPic)
                {
                    LoadPicture(imgPath[0]);
                    currentPic = 1;
                }
                else
                {
                    LoadPicture(imgPath[currentPic]);
                    currentPic++;
                }
                CheckPic();
                lblPicNum.Text = currentPic.ToString() + "/" + numPic.ToString();
            }
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            if (hasImage)
            {
                LoadPicture(imgPath[currentPic - 1]);
                CheckPic();
            }
        }

        private void pgConfig_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
        {
          //  pgConfig.SelectedObject = config;
     
        }

        private void btnSaveConfig_Click(object sender, EventArgs e)
        {

            string res = config.Save();
            if (res != "")
            {
                MessageBox.Show(res, "Error Saving Configuration", MessageBoxButtons.OK);
            }
        }

        private void btnReloadConfig_Click(object sender, EventArgs e)
        {
            if (config != null)
            {
                config.Load(ref config);
                propertyGrid1.Refresh();
        

             //   pgConfig.Refresh();
            }
        }

        #region MouseEvent

        private double _zoom = 1;
        private void ZoomWork(double zoom, MouseEventArgs e)
        {
            if (_zoom >= 40 || _zoom <= 0.05)
            {
                if (zoom > 1)
                {
                    _zoom /= 1.1;
                }
                else
                {
                    _zoom /= 0.9;
                }
                return;
            }
            try
            {

                int x0, y0, x1, y1, x2, y2, x3, y3;

                //(x1,y1)鼠标点在原PictureBxo中的坐标
                x1 = e.Location.X;
                y1 = e.Location.Y;
                //zoom后，鼠标点也产生偏移，(x2,y2)为鼠标点在zoom后PictureBxo中的坐标
                x2 = (int)(e.Location.X * zoom);
                y2 = (int)(e.Location.Y * zoom);

                //(x0,y0)偏移后的鼠标点在imgPanel中的坐标
                x0 = x2 + imgPictureBox.Left - (int)((zoom - 1) * imgPictureBox.Width / 2);
                y0 = y2 + imgPictureBox.Top - (int)((zoom - 1) * imgPictureBox.Height / 2);

                //(x3,y3)为zoom后未平移前，PictureBox的左上角在imgPanel中的坐标
                x3 = imgPictureBox.Left - (int)((zoom - 1) * imgPictureBox.Width / 2);
                y3 = imgPictureBox.Top - (int)((zoom - 1) * imgPictureBox.Height / 2);

                imgPictureBox.Width = (int)(imgPictureBox.Width * zoom);
                imgPictureBox.Height = (int)(imgPictureBox.Height * zoom);
                //将偏移后的鼠标点，平移到imgPanel中心
                imgPictureBox.Left = imgPictureBox.Left + x1 - x2;
                imgPictureBox.Top = imgPictureBox.Top + y1 - y2;
            }
            catch
            {


            }
           
        }

        private void imgPictureBox_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            imgPictureBox.Focus();
        }

        private void imgPictureBox_MouseDown(object sender, MouseEventArgs e)
        {
            draw = true;
        //    this.imgPictureBox.Invalidate();
            if (IsDrawretangle == true)
            {
                if (e.Button == MouseButtons.Left)
                {
                    startPoint = new Point(e.X, e.Y);
                    isDrag = true;
                }
            }
            else
            {
                _isMouseDown = true;
                _mousePosA = e.Location;

            }

        }

        private void imgPictureBox_MouseEnter(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
            imgPictureBox.Focus();
        }

        private void imgPictureBox_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Default;
        }

        private void imgPictureBox_MouseMove(object sender, MouseEventArgs e)
        {
            draw = true;
            if (IsDrawretangle == true)
            {
                if (isDrag)
                {
                    var pictureBox = sender as PictureBox;
                    Graphics g = pictureBox.CreateGraphics();
                    g.DrawRectangle(new Pen(Color.Green, 2), startPoint.X, startPoint.Y, e.X - startPoint.X, e.Y - startPoint.Y);
                 //   pictureBox.Invalidate();
                }
            }
            else
            {

                try
                {
                    tstPosition.Text = string.Format("{0},{1}", (int)(e.X), (int)(e.Y));
                    if (imgPictureBox.Image != null)
                    {
                        var bitmap = imgPictureBox.Image as Bitmap;
                        if (bitmap != null)
                        {
                            int realX = Convert.ToInt32((double)e.X * ((double)bitmap.Width / (double)imgPictureBox.Width));
                            int realY = Convert.ToInt32((double)e.Y * ((double)bitmap.Width / (double)imgPictureBox.Width));
                            Color bmpColor = bitmap.GetPixel(realX, realY);
                            tslGray.Text = ((bmpColor.R + bmpColor.G + bmpColor.B) / 3).ToString();
                        }
                    }
                    if (!_isMouseDown || e.Button != MouseButtons.Left) return;
                    var pictureBox = sender as PictureBox;
                    //if (pictureBox != null) pictureBox.Left += e.Location.X - _mousePosA.X;
                    //var box = sender as PictureBox;
                    //if (box != null) box.Top += e.Location.Y - _mousePosA.Y;

                    if (pictureBox != null)
                    {
                        pictureBox.Left += e.Location.X - _mousePosA.X;
                        pictureBox.Top += e.Location.Y - _mousePosA.Y;

                    }
                }
                catch (Exception ex)
                {
                }
            }

            this.imgPictureBox.Invalidate();


        }
        #endregion

        private void imgPictureBox_MouseUp(object sender, MouseEventArgs e)
        {

            draw = true;
            this.imgPictureBox.Invalidate(); 
            
            var pictureBox = sender as PictureBox;
            double grayvalue = 0;
            if (IsDrawretangle == true)
            {
                if (e.Button == MouseButtons.Left)
                {

                   try
                    { 
                    ig = pictureBox.CreateGraphics();
                    ig.DrawRectangle(new Pen(Color.Green, 2), startPoint.X, startPoint.Y, e.X - startPoint.X, e.Y - startPoint.Y);
                    theRectangle = new Rectangle(startPoint.X, startPoint.Y, e.X - startPoint.X, e.Y - startPoint.Y);
                    isDrag = false;
                   // pictureBox.Invalidate();

                    Graphics graphics = this.CreateGraphics();

                    Bitmap bitmap = new Bitmap(pictureBox.Image);

                    Bitmap cloneBitmap = bitmap.Clone(theRectangle, PixelFormat.DontCare);

                    grayvalue = EvaluteImageCore.CalculGrayMean(cloneBitmap);

                    if (IsSaveimage == true)
                    {                                           
                            string imageName = System.DateTime.Now.Year.ToString() + "-" + System.DateTime.Now.Month.ToString() +
                                "-" + System.DateTime.Now.Day.ToString() + "-" + System.DateTime.Now.Hour.ToString() + "-" + System.DateTime.Now.Minute.ToString()
                                + "-" + System.DateTime.Now.Second.ToString() + "-" + System.DateTime.Now.Millisecond.ToString() + ".bmp";

                            string SavePathTemp = AppDomain.CurrentDomain.BaseDirectory + "screenshot";
                            string SavePath = null;

                            if (!Directory.Exists(SavePathTemp))
                            {
                                Directory.CreateDirectory(SavePathTemp);
                            }                         
                            SavePath = SavePathTemp + "\\"+imageName;
                            cloneBitmap.Save(SavePath);

                            //Graphics g = pictureBox.CreateGraphics();
                            //Font drawFont = new Font("Arial", 16);
                            //SolidBrush myBrush = new SolidBrush(Color.Red);
                            //g.DrawString("灰度均值" + grayvalue.ToString("F3"), drawFont, myBrush, theRectangle);                          
                            MessageBox.Show("图像截取完毕！");                      
                    }
                         }
                        catch
                        { }

                    if(IsDisplayGray==true)
                    {
                        Graphics g = pictureBox.CreateGraphics();
                        Font drawFont = new Font("Arial", 7);
                        SolidBrush myBrush = new SolidBrush(Color.Red);
                        g.DrawString(grayvalue.ToString("F3"), drawFont, myBrush, theRectangle);
                    }
                    pictureBox.Invalidate();
           
                }
               }
                
            
        }

        private void imgPictureBox_MouseClick(object sender, MouseEventArgs e)
        {
            //imgPictureBox.Invalidate();
            //var pictureBox = sender as PictureBox;
            //if (IsSaveimage == true)
            //{
            //    if (IsDrawretangle == true)
            //    {
            //        try
            //        {
            //            Graphics graphics = this.CreateGraphics();
            //            Bitmap bitmap = new Bitmap(pictureBox.Image);
            //            Bitmap cloneBitmap = bitmap.Clone(theRectangle, PixelFormat.Format8bppIndexed);

            //            string imageName = System.DateTime.Now.Year.ToString() + "-" + System.DateTime.Now.Month.ToString() +
            //                "-" + System.DateTime.Now.Day.ToString() + "-" + System.DateTime.Now.Hour.ToString() + "-" + System.DateTime.Now.Minute.ToString()
            //                + "-" + System.DateTime.Now.Second.ToString() + "-" + System.DateTime.Now.Millisecond.ToString()+".bmp";

                     
            //            cloneBitmap.Save(imageName);
            //            Graphics g = pictureBox.CreateGraphics();
            //            SolidBrush myBrush = new SolidBrush(Color.White);
            //            g.FillRectangle(myBrush, theRectangle);

            //            MessageBox.Show("图像截取完毕！");
            //            pictureBox.Invalidate();
            //        }
            //        catch
            //        { }

            //    }
            //}
        }
        /// <summary>
        /// 画ROI矩形
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cxB_DrawRectangele_CheckedChanged(object sender, EventArgs e)
        {
                           
            imgPictureBox.Invalidate();
            if (cxB_DrawRectangele.CheckState == CheckState.Checked)
            {
              IsDrawretangle = true;
                

            }
            else
            {
                IsDrawretangle = false;
            }
        }
        /// <summary>
        /// 保存截取区域选项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chB_Saveimg_CheckedChanged(object sender, EventArgs e)
        {
            imgPictureBox.Invalidate();
            if (chB_Saveimg.CheckState == CheckState.Checked)
            {
                IsSaveimage = true;
            }
            else
            {
                IsSaveimage = false;

            }
        }
        /// <summary>
        /// 图像正常显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chB_NormalSize_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (chB_NormalSize.Checked)
                {
                    imgPictureBox.Width = _bitmap.Width;
                    imgPictureBox.Height = _bitmap.Height;
                    imgPictureBox.Invalidate();
                    chB_AtuoSize.CheckState = CheckState.Unchecked;
                }
            } 
            catch
            {
            }
          
           
        }
        /// <summary>
        /// 图像适应窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chB_AtuoSize_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (chB_AtuoSize.CheckState == CheckState.Checked)
                {
                    imgPictureBox.Width = _bitmap.Width / 4;
                    imgPictureBox.Height = _bitmap.Height / 4;
                    imgPictureBox.Invalidate();
                    chB_NormalSize.CheckState = CheckState.Unchecked;
                }
            }
            catch { }
          
        }

        private void chB_Calulatgray_CheckedChanged(object sender, EventArgs e)
        {
            if(chB_Calulatgray.CheckState==CheckState.Checked)
            {
                IsDisplayGray = true;
            }
            else
            {
                IsDisplayGray = false;

            }
        }

    }
}